package com.wit.witmg.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wit.witmg.entity.*;
import com.wit.witmg.mapper.TMatOutputMapper;
import com.wit.witmg.mapper.TProdtaskMapper;
import com.wit.witmg.service.ITMatOutputService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wit.witmg.service.ITProdstockService;
import com.wit.witmg.util.ErrorCode;
import com.wit.witmg.util.JsonResult;
import com.wit.witmg.util.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author bob
 * @since 2025-01-16
 */
@Service
@RequiredArgsConstructor
public class TMatOutputServiceImpl extends ServiceImpl<TMatOutputMapper, TMatOutput> implements ITMatOutputService {

    final ITProdstockService prodstockService;
    final TProdtaskMapper prodtaskMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object add(HttpServletRequest request, String json) {
        if(StringUtils.instance.isEmpty(json)){
            return JsonResult.error(ErrorCode.ERR_200);
        }
        if(json.contains("[") && json.contains("]")){
            List<TMatOutput> list= JSON.parseArray(json,TMatOutput.class);
            boolean bl= saveBatch(list);
            if (!bl) {
                return JsonResult.error(ErrorCode.ERR_504);
            }
            return JsonResult.success(list);
        }else {
            // //参数id单条修改；当stat为1时：需联表根据bn查询库存表获取库存数量qt和库存金额amount，把出库表的amount=出库表oqt*库存表amount/库存表qt，
            //                // 再把库存表qt-出库表oqt，把库存表amount-出库表amount;把计划表中的amount+=amount；
            TMatOutput t = JSON.parseObject(json, TMatOutput.class);
            QueryWrapper<TProdstock> qw = new QueryWrapper<>();
            qw.eq("bn", t.getBn());
            qw.last("limit 1");
            TProdstock prodstock = prodstockService.getOne(qw);
            if(prodstock==null){
                return JsonResult.error(ErrorCode.ERR_201);
            }
           double amount= prodstock.getAmount()/prodstock.getQt()*t.getOqt();
            prodstock.setAmount(prodstock.getAmount()-amount);
            prodstock.setQt(prodstock.getQt()-t.getOqt());

            //修改计划表
           boolean bl= prodtaskMapper.updateAmount(t.getPid(),amount);

            if(!bl){
                return JsonResult.error(ErrorCode.ERR_504);
            }
            t.setAmount(amount);

            if (t.getId() > 0) {

                 bl = updateById(t);
                if (!bl) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚
                    return JsonResult.error(ErrorCode.ERR_504);
                }

            } else {
                bl = save(t);
                if (!bl) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//回滚
                    return JsonResult.error(ErrorCode.ERR_504);
                }
            }
            return JsonResult.success(t);
        }
    }

    @Override
    public Object get(HttpServletRequest request, Long eid, Integer oid, Integer pid, String bn) {
        QueryWrapper<TMatOutput> qw=new QueryWrapper<>();
        if(eid!=null){
            qw.eq("eid",eid);
        }
        if(pid!=null){
            qw.eq("pid",pid);
        }
        if(oid!=null){
            qw.eq("oid",oid);
        }
        if(bn!=null){
            qw.like("bn",bn);
        }
        return JsonResult.success(list(qw));
    }
}
